package com.tbl.modules.wms.controller.outstorage;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.tbl.common.utils.DateUtils;
import com.tbl.common.utils.PageTbl;
import com.tbl.common.utils.PageUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.platform.constant.LogActionConstant;
import com.tbl.modules.platform.constant.MenuConstant;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.LogService;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.platform.util.DeriveExcel;
import com.tbl.modules.wms.entity.outstorage.ShipLoading;
import com.tbl.modules.wms.service.outstorage.ShipLoadingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 出库管理：装车发运
 * @author 70486
 */
@Controller
@RequestMapping("/deleiveryCon")
public class DeliveryController extends AbstractController {

    /**
     * 出库管理-装车发运
     */
    @Autowired
    private ShipLoadingService shipLoadingService;
    /**
     * 日志信息
     */
    @Autowired
    private LogService logService;
    /**
     * 角色信息
     */
    @Autowired
    private RoleService roleService;

    /**
     * 跳转到装车发运页面
     * @return ModelAndView
     */
    @RequestMapping("/deleiveryCList.do")
    public ModelAndView storageList() {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("operationCode", roleService.selectOperationByRoleId(getSessionUser().getRoleId(), MenuConstant.deleiveryCon));
        mv.setViewName("techbloom/outstorage/delivery/delivery_list");
        return mv;
    }

    /**
     * 装车发运列表页数据
     * @param queryJsonString 查询条件
     * @return Map<String,Object> 列表结果集
     */
    @RequestMapping(value = "/shipLoadingPageList.do")
    @ResponseBody
    public Map<String, Object> shipLoadingPageList(String queryJsonString) {
        Map<String, Object> map = new HashMap<>(3);
        if (!StringUtils.isEmptyString(queryJsonString)) {
            map = JSON.parseObject(queryJsonString);
        }
        PageTbl page = this.getPage();
        PageUtils utils = shipLoadingService.getPageList(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("rows", utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        return map;
    }

    /**
     * 点击新增跳转到新增页面
     * @return ModelAndView
     */
    @RequestMapping(value = "/toAdd.do")
    @ResponseBody
    public ModelAndView execute() {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("info",new ShipLoading());
        mv.setViewName("techbloom/outstorage/delivery/delivery_add");
        return mv;
    }

    /**
     * 根据主键获取到详情的列表
     * @param id 装车发运表主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/detailList.do")
    @ResponseBody
    public Map<String, Object> detailList(Integer id) {
        Map<String, Object> map = new HashMap<>(2);
        PageTbl page = this.getPage();
        PageUtils utils = shipLoadingService.getPageDetailList(page, id);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("rows", utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        return map;
    }

    /**
     * 点击查看，跳转到详情列表页
     * @param id 装车发运主键
     * @return ModelAndView
     */
    @RequestMapping(value = "/toInfo.do")
    @ResponseBody
    public ModelAndView toInfo(Long id) {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("info", shipLoadingService.selectById(id));
        mv.setViewName("techbloom/outstorage/delivery/delivery_info");
        return mv;
    }

    /**
     * 点击编辑，跳转到编辑页面
     * @param id 装车发运主键
     * @return ModelAndView
     */
    @RequestMapping(value = "/editInfo.do")
    @ResponseBody
    public ModelAndView editInfo(Long id) {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("info", shipLoadingService.selectById(id));
        mv.setViewName("techbloom/outstorage/delivery/delivery_edit");
        return mv;
    }


    /**
     * 导出Excel
     * @param request
     * @param response
     */
    @RequestMapping(value = "/materialExcel", method = RequestMethod.POST)
    @ResponseBody
    public void materialExcel(HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> map = new HashMap<>();
        map.put("shipLoadTime", request.getParameter("queryShipLoadTime"));
        map.put("ids", StringUtils.stringToInt(request.getParameter("ids")));

        try {
            String sheetName = "装车发运" + "(" + DateUtils.getDay() + ")";
            response.setHeader("Content-Type", "application/force-download");
            response.setHeader("Content-Type", "application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(sheetName.getBytes("gbk"),
                    "ISO8859-1") + ".xls");

            Map<String, String> mapFields = new LinkedHashMap<>();
            mapFields.put("shipLoadTime", "装车时间");
            mapFields.put("shipLoadUserName", "装车人");
            mapFields.put("licensePlate", "车牌号");
            DeriveExcel.exportExcel(sheetName, shipLoadingService.getExcelList(map), mapFields, response, "");
            logService.logInsert("装车发运导出", LogActionConstant.USER_EXPORT, request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 点击编辑，点击保存  保存主表信息
     * @param shipLoading 装车发运
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/saveShipLoading")
    @ResponseBody
    public Map<String, Object> saveShipLoading(ShipLoading shipLoading) {
        Map<String, Object> map = new HashMap<>(3);
        shipLoading.setShipLoadUserName(getSessionUser().getUsername());
        shipLoading.setShipLoadUserId(getSessionUser().getUserId());
        shipLoading.setShipLoadTime(new Date());
        Long id = shipLoadingService.saveShipLoading(shipLoading);
        map.put("result", true);
        map.put("msg", id>0?"保存成功！":"保存失败！");
        map.put("shipLoadingId", id);
        return map;
    }

    /**
     * 点击编辑，点击提交，修改状态
     * @param id 装车发运主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/subShiploading")
    @ResponseBody
    public Map<String, Object> subShiploading(Long id) {
        Map<String, Object> map = Maps.newHashMap();
        ShipLoading shipLoading = shipLoadingService.selectById(id);
        shipLoading.setShipLoadUserId(getUserId());
        boolean result = shipLoadingService.subShiploading(shipLoading);
        map.put("result", result);
        map.put("msg", result?"提交成功！":"提交失败！");
        return map;
    }

    /**
     * 点击编辑，获取质保单号列表
     * @param pageSize 页大小
     * @param pageNo 页码
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/getQaCode")
    @ResponseBody
    public Map<String, Object> getQaCode(int pageSize, int pageNo) {
        Map<String, Object> map = Maps.newHashMap();
        PageTbl page = this.getPage();
        page.setPagesize(pageSize);
        page.setPageno(pageNo);
        PageUtils utils = shipLoadingService.getQaCode(page, map);
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        map.put("result", utils.getList() == null ? "" : utils.getList());
        return map;
    }

    /**
     * 点击编辑，装车发运详情添加
     * @param id 装车发运主表主键
     * @param qaCodeIds 出库详情主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/saveShipLoadingDetail")
    @ResponseBody
    public Map<String, Object> saveShipLoadingDetail(Long id, String[] qaCodeIds) {
        Map<String, Object> map = Maps.newHashMap();
        boolean result = shipLoadingService.saveShipLoadingDetail(id, qaCodeIds);
        map.put("result", result);
        map.put("msg", result?"添加成功！":"添加失败！");
        return map;
    }

    /**
     * 点击编辑，删除装车发运明细数据
     * @param ids 装车发运明细主键列表
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/deleteShipLoadingDetailIds")
    @ResponseBody
    public Map<String, Object> deleteShipLoadingDetailIds(String[] ids) {
        Map<String, Object> map = Maps.newHashMap();
        boolean result = shipLoadingService.deleteShipLoadingDetailIds(ids);
        map.put("msg", result ? "删除成功！" : "删除失败！");
        map.put("result", result);
        return map;
    }

    /**
     * 删除
     * @param ids 装车发运主表主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/deleteByIds")
    @ResponseBody
    public Map<String, Object> deleteByIds(String[] ids) {
        Map<String, Object> map = Maps.newHashMap();
        boolean result = shipLoadingService.deleteByIds(ids);
        map.put("msg", result ? "删除成功！" : "删除失败！");
        map.put("result", result);
        return map;
    }


}
